<template>
  <div class="swiper-container" v-if="showSwiper">
      <div class="swiper-wrapper" >
        <ul class="swiper-slide swiper_list" >
          <li class="swiper_list_son" v-for="item of swiper " :key="item.id">
            <img class="img_c1" :src="item.img" alt="">
            <p>{{item.title}}</p>
          </li>
        </ul>
      </div>
      <!-- Add Pagination -->
      <div class="swiper-pagination"></div>
  </div>
</template>

<script>
import Swiper from 'swiper'
import 'swiper/dist/css/swiper.min.css'

export default {
  name: 'HomeSwiper',
  data () {
    return {
      mySwiper: null
    }
  },
  computed: {
    showSwiper () {
      return this.swiper.length // 解决获取图片的时候第一个为空
    }
  },
  mounted () {
    // alert("第五步")
    this.swiperUpdate() // 页面一加载拉去数据创建节点
  },
  methods: {
    _initSwiper () { // 创建节点
      // alert("第一步")
      this.mySwiper = new Swiper('.swiper-container', {
        loop: true,
        pagination: {
          el: '.swiper-pagination',
          clickable: true
        }
      })
    },
    _updateSwiper () {
      // alert("第二步")
      this.$nextTick(() => { // swiper动态更新
        this.mySwiper.update(true) // swiper update的方法
      })
    },
    swiperUpdate () {
      // alert("第三步")
      if (this.mySwiper) { // 节点存在
        this._updateSwiper() // 更新
      } else {
        this._initSwiper() // 创建
      }
    }
  },
  watch: {
    // 通过props传来的数据 和 组件一加载节点就创建成功 二者不是同步，实时监听的swiper(传递的值)的变化
    swiper () {
      // alert("第四步")
      this.swiperUpdate()
    }
  }
}
</script>

<style lang="stylus" scoped>
  .swiper-container >>> .swiper-pagination-bullet-active
    background: #25a4bb
    opacity 1!important
  .swiper-container >>> .swiper-pagination-bullet
    opacity .3
    width 12px
    height 12px
  .swiper-container >>> .swiper-container-horizontal > .swiper-pagination-bullets
    bottom: 0.16rem
  .swiper-container
    width 100%
    height 400px;
    overflow hidden
    padding-top 90px
    .swiper_list
      background white
      display flex
      flex-direction row
      flex-wrap wrap
      align-content stretch
      .swiper_list_son
        float left
        width 25%
        text-align center
        margin-bottom 30px
        img
          width 100px
        p
          font-size 23px
          margin-top 20px

</style>
